package com.toune.villager.model

import androidx.lifecycle.MutableLiveData
import com.tamsiree.rxkit.view.RxToast
import com.toune.dltools.ui.DLBaseViewModel
import com.zia.easybookmodule.bean.Book
import com.zia.easybookmodule.bean.Catalog
import com.zia.easybookmodule.bean.Chapter
import com.zia.easybookmodule.engine.EasyBook
import com.zia.easybookmodule.rx.Disposable
import com.zia.easybookmodule.rx.StepSubscriber
import com.zia.easybookmodule.rx.Subscriber

class BookModel : DLBaseViewModel() {
    lateinit var subscribe: Disposable
    val books = MutableLiveData<List<Book>>()
    val mCatalogs = MutableLiveData<List<Catalog>>()
    fun searchBook(searchStr: String) {
        loadingSate.postValue(true)
        Thread {
            subscribe = EasyBook.search(searchStr)
                .subscribe(object : StepSubscriber<List<Book>> {
                    override fun onFinish(t: List<Book>) {
                        books.postValue(t)
                    }

                    override fun onError(e: Exception) {
                        e.printStackTrace()
                    }

                    override fun onMessage(message: String) {
                        RxToast.showToast(message)
                    }

                    override fun onProgress(progress: Int) {
                    }

                    override fun onPart(t: List<Book>) {
                    }

                })
        }.start()
    }

    fun getCatalog(book: Book) {
        Thread {
            subscribe = EasyBook.getCatalog(book)
                .subscribe(object : Subscriber<List<Catalog>> {
                    override fun onFinish(catalogs: List<Catalog>) {
                        //加载结果，返回该书籍所有目录
                        mCatalogs.postValue(catalogs)
                    }

                    override fun onError(e: java.lang.Exception) {
                    }

                    override fun onMessage(message: String) {
                        RxToast.showToast(message)
                    }

                    override fun onProgress(progress: Int) {
                    }
                })

        }.start()
    }

    override fun onCleared() {
        super.onCleared()
        subscribe.dispose()
    }
}